package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        log.error("线程id={}",Thread.currentThread().getId());
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //1.获取用户uri
        String requestURI = request.getRequestURI();
        log.info("我开始拦截了->{}",requestURI);

        //2.放行页面和登录相关的接口(白名单)
        String[] uris = {
                "/front/**",
                "/backend/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg", //发送验证码
                "/user/login"  //用户登录
        };
        boolean check = check(uris, requestURI);
        if(check){
            log.info("放行路径{}",requestURI);
            chain.doFilter(request, response);//放行
            return; //终止程序 不往下走了
        }
        //判断用户登录状态 登录成功 放行
        if(request.getSession().getAttribute("userId")!=null){
            log.info("用户登录成功,登录id为:{}",request.getSession().getAttribute("userId"));
            Long userId = (Long) request.getSession().getAttribute("userId");
            BaseContext.setCurrentId(userId);
            chain.doFilter(request,response);
            return;
        }
        //3.登录成功 -> 彻底放行
        HttpSession session = request.getSession();
        Object employee = session.getAttribute("employee");
        if(employee!=null){
            log.info("已经登录放行{}",requestURI);
            //获取HttpSession中的登录用户信息
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            chain.doFilter(request, response);
            return;
        }
        //最后  ->  拦截  -> 响应一个结果notlogin
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配器
     * @param uris 白名单
     * @param requestURI 测试路径
     * @return 如果返回true 放行  false 拦截
     */
    public boolean check(String[] uris,String requestURI){
        AntPathMatcher matcher = new AntPathMatcher();
        for (String uri : uris) {
            if (matcher.match(uri,requestURI)) {
                return true;
            }
        }
        return false;
    }
}
